package com.soladhoc.annonces.client.ui;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Button;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import com.soladhoc.annonces.client.place.NameTokens;
import com.soladhoc.annonces.shared.proxy.AnnonceProxy;
import com.soladhoc.annonces.shared.service.AnnonceRequestFactory;
import com.soladhoc.annonces.shared.service.AnnonceRequestFactory.AnnonceService;

public class AnnoncePresenter extends
		Presenter<AnnoncePresenter.MyView, AnnoncePresenter.MyProxy> {

	final AnnonceRequestFactory requestFactory;
	
	public interface MyView extends View {
		void setTitle(String title);
		String getTitle();
		
		void setText(String text);
		String getText();
		
		Button getSaveButton();
		void setError(String text);
	}

	@ProxyCodeSplit
	@NameToken(NameTokens.annonce)
	public interface MyProxy extends ProxyPlace<AnnoncePresenter> {
	}

	@Inject
	public AnnoncePresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy, final AnnonceRequestFactory requestFactory) {
		super(eventBus, view, proxy);
		this.requestFactory = requestFactory;
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, MainPagePresenter.CENTRAL_SLOT_TYPE, this);
	}

	@Override
	protected void onBind() {
		super.onBind();
		this.registerHandler(getView().getSaveButton().addClickHandler(
				new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						AnnoncePresenter.this.saveAnnonce();
					}
				}
		));
	}
	
	private void saveAnnonce(){
		getView().setError("");
		String title = getView().getTitle();
		String text = getView().getText();
		// save annonce
		AnnonceService reqCtx = this.requestFactory.annonceService();
		AnnonceProxy annonceProxy = reqCtx.create(AnnonceProxy.class);
		annonceProxy.setTitle(title);
		annonceProxy.setText(text);
		reqCtx.save(annonceProxy);
	}

	@Override
	public void prepareFromRequest(PlaceRequest request) {
		getView().setTitle(request.getParameter("title", "title"));
		super.prepareFromRequest(request);
	}
	
	
	
}
